from flask import Blueprint, request, jsonify, make_response, render_template

from constant.BlogConstant import BlogConstant
from service.UserService import assemble_user_qq_login, save_user_by_qq, get_user_by_account
from util.LoginUtil import set_login_info
from util.OAuthQQ import OAuthQQ

view_login = Blueprint('view_login', __name__)
view_login.url_prefix = '/view/login'


@view_login.route("/qq")
def qq_login():
    # 获取前端传入的code
    code = request.args.get("code")
    # 判断是否有,如果没有直接return
    if not code:
        return jsonify({'message': 'not find code'})
    oauth = OAuthQQ()
    try:
        # 使用code向QQ服务器请求access_token
        access_token = oauth.get_qq_access_token(code)
        # 使用access_token获取openid
        openid = oauth.get_openid(access_token)
    except:
        return jsonify({'message': 'QQ exist error'})
    user = get_user_by_account(openid, BlogConstant.user_type_qq)
    # save user message
    if user is None:
        user_info = oauth.get_user_info(access_token, openid)
        user = assemble_user_qq_login(user_info, openid)
        save_user_by_qq(user)
        user = get_user_by_account(openid, BlogConstant.user_type_qq)
    view = render_template("common/login-success.html")
    response = make_response(view)
    login_info = {
        "avatar": user.avatar,
        "is_admin": user.is_admin,
        "nick_name": user.nick_name,
        "uuid": user.uuid,
        "username": user.nick_name
    }
    set_login_info(response, login_info)
    return response


@view_login.route("")
def login():
    return render_template('common/login.html')
